package com.ocom.exposeapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.ExposeApiUrl;
import com.ocom.common.constant.MapKey;
import com.ocom.common.dto.AddDeptDto;
import com.ocom.common.entity.access.EntityDeptInfo;
import com.ocom.common.entity.company.EntityComDockApi;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.entity.master.EntityWechatPerInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.company.GetReplyApiParaRequest;
import com.ocom.common.request.exposeapi.CCBCuserInfoRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.*;
import com.ocom.common.vo.PersonVo;
import com.ocom.common.vo.human.UserInfoVo;
import com.ocom.exposeapi.feign.CompanyClientService;
import com.ocom.exposeapi.feign.HumanFeignService;
import com.ocom.exposeapi.feign.MqSimple;
import com.ocom.exposeapi.vo.ccb.XyyjRegisterRequest;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author: 朱晖 建行接口
 * @Date: 2023/5/22
 **/
@Slf4j
@RestController
public class CcbController {


	@Autowired
	private CompanyClientService companyClientService;

	@Autowired
	HumanFeignService humanFeignService;

	@Autowired
	MqSimple mqSimpleFeign;

	/**
	 * campusId	学校应用编号	string		是
	 * pName	用户姓名	string		是
	 * pCode	用户编号	string		是
	 * nonceStr
	 * sign
	 * 应答:
	 * 参数	名称	类型（字节）	参数说明	必填项
	 * code	错误码	int	0成功，1失败	必填
	 * msg	错误信息	string
	 * pName	用户姓名	string		是
	 * pCode	用户编号	string		是
	 * deptName	部门名称	string
	 * pPhotoUrl	人脸头像连接	string
	 */

	//获取人员
	@PostMapping(ExposeApiUrl.URL_ExposeApiCcbUserInfo)
	public Result CcbUserInfo(@Valid @RequestBody CCBCuserInfoRequest request, BindingResult bindingResult){
		//验sign
		if (bindingResult.hasErrors()) {
			return ResultUtil.info(500,bindingResult.getAllErrors().get(0).getDefaultMessage());
		}

		String sign = request.getSign().toLowerCase();

		JHh5 jHh5 = getCompany(request.getCampusId());
		if(jHh5.getCode()!=0){
			return ResultUtil.info(501,jHh5.getMsg());
		}

		if(jHh5.getComId()==null || jHh5.getComId()<=0l){
			return ResultUtil.error(ResultEnum.Err_301);
		}

		SortedMap<String, Object> parameters = new TreeMap<>();
		parameters.put("campusId",request.getCampusId());
		parameters.put("pName",request.getPName());
		parameters.put("pCode",request.getPCode());
		parameters.put("nonceStr",request.getNonceStr());

		String sign1 = SignUtils.createSign(parameters, "EObOqA6WtLIpxX61UOEZVyzJTUsiiQ9E");
		System.out.println(sign1);
		if (!sign.equals(sign1)) {
			return ResultUtil.error(ResultEnum.Err_202);
		}
		UserInfoVo userInfoVo = new UserInfoVo();
		userInfoVo.setComId( jHh5.getComId());
		userInfoVo.setPCode(request.getPCode());
		userInfoVo.setOnlyOne(true);
		Result result2  = humanFeignService.PersonnelGetPersonInfo(userInfoVo);
		if(result2.getCode()!=200 || result2.getData()==null){
			return ResultUtil.error(ResultEnum.Err_303);
		}
		EntityPersonnelInfo entityPersonnelInfo = JSON.parseObject(JSON.toJSONString(result2.getData()),EntityPersonnelInfo.class);

		Result result3 = humanFeignService.getXfUserInfo(entityPersonnelInfo.getComId(),entityPersonnelInfo.getPId());
		if(result3.getCode()!=200 || result3.getData()==null){
			return ResultUtil.error(ResultEnum.Err_303);
		}
		return result3;
	}

	//学有优教登录注册
	@PostMapping(ExposeApiUrl.URL_ExposeApixyyjRegister)
	public Result xyyjRegister(@Valid @RequestBody XyyjRegisterRequest request, BindingResult bindingResult) {
	//	Long comId = request.getUserData().getCampusId();
		log.info("学有优教登录注册登录 参数【{}】",request);
		Long comId = request.getComId();

		GetReplyApiParaRequest getReplyApiParaRequest = new GetReplyApiParaRequest();
		getReplyApiParaRequest.setComId(comId);
		getReplyApiParaRequest.setDockCode("ccbplatform");
		getReplyApiParaRequest.setDockApiCode("appnavigate#xyyjRegister");
		getReplyApiParaRequest.setKeyType(0);
		Result result2 = companyClientService.getReplyApiPara(getReplyApiParaRequest);

		if (result2.getCode() != 200) {
			return result2;
		}
		EntityComDockApi entityComDockApi = JSON.parseObject(JSON.toJSONString(result2.getData()), EntityComDockApi.class);

		JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(request));
		jsonObject.put("userData",null);
		String sign = SignUtils.createSign(jsonObject,null,"key",entityComDockApi.getKey());
		if(!sign.equals(request.getSign())){
			return ResultUtil.error(ResultEnum.Err_202);
		}

		Result result3 = humanFeignService.getDeptList(comId, 0l, 0);

		List<EntityDeptInfo> list = JSON.parseArray(JSON.toJSONString(result3.getData()), EntityDeptInfo.class);

		Long gradeDeptId = 0l;
		Long deptId = 0l;
		if(!CommonUtil.isNull(request.getUserData().getGradeName())
		&& !CommonUtil.isNull(request.getUserData().getDeptName())){
			List<Long> list1 = list.stream()
					.filter(o -> o.getGrade()==1l)
					.filter(o -> o.getDeptType()==10 )
					.filter(o -> o.getDeptName().equals(request.getUserData().getGradeName()))
					.map(EntityDeptInfo::getDeptId).collect(Collectors.toList());

			if(list1!=null  && list1.size()>0){
				gradeDeptId = list1.get(0);
			}else{
				//添加
				AddDeptDto addDeptDto=new AddDeptDto();
				addDeptDto.setComId(comId);
				addDeptDto.setDeptName(request.getUserData().getGradeName());
				addDeptDto.setDeptType(10);
				addDeptDto.setParentDeptId(0l);
				Result result6 = humanFeignService.AddDeptInfo(addDeptDto);
				if(result6.getCode()==200){
					gradeDeptId = ((Integer) result6.getData()).longValue();
				}
			}
			if(gradeDeptId ==null) gradeDeptId=0l;
			final Long parDept = gradeDeptId;
			List<Long> list2 = list.stream()
					.filter(o -> o.getGrade()==2l)
					.filter(o -> o.getDeptType()==20 )
					.filter(o -> o.getParentDeptId().equals(parDept) )
					.filter(o -> o.getDeptName().equals(request.getUserData().getDeptName()))
					.map(EntityDeptInfo::getDeptId).collect(Collectors.toList());

			if(list2!=null  && list2.size()>0){
				deptId = list2.get(0);
			}else{
				//添加
				AddDeptDto addDeptDto=new AddDeptDto();
				addDeptDto.setComId(comId);
				addDeptDto.setDeptName(request.getUserData().getDeptName());
				addDeptDto.setParentDeptId(gradeDeptId);
				addDeptDto.setDeptType(20);
				Result result6 = humanFeignService.AddDeptInfo(addDeptDto);
				if(result6.getCode()==200){
					deptId = ((Integer) result6.getData()).longValue();
				}
				if(deptId ==null) deptId=0l;
			}
		}






		String pcode = request.getUserData().getPCode();

		UserInfoVo userInfoVo = new UserInfoVo();
		userInfoVo.setComId(comId);
		userInfoVo.setPCode(pcode);
		userInfoVo.setOnlyOne(true);
		Result result4 = humanFeignService.PersonnelGetPersonInfo(userInfoVo);

		EntityPersonnelInfo entityPersonnelInfo = null;

		if (result4.getCode() != 200) {
			// 插入人员
			PersonVo personVo=new PersonVo();
			personVo.setComId(comId);
			personVo.setPCode(pcode);
			personVo.setPName(request.getUserData().getPName());
			personVo.setDeptId(deptId);
            Result result5 =humanFeignService.AddPerson(personVo) ;
//			return result4;
            entityPersonnelInfo = JSON.parseObject(JSON.toJSONString(result5.getData()), EntityPersonnelInfo.class);

			if(entityPersonnelInfo!=null){
				Map<String, Object> map = new HashMap<>();
				MapKey mapKey = new MapKey();
				map.put(mapKey.getKey_pId(), entityPersonnelInfo.getPId());
				map.put(mapKey.getKey_comId(), entityPersonnelInfo.getComId());
				map.put(mapKey.getKey_accountNo(), entityPersonnelInfo.getComId() + "P" + entityPersonnelInfo.getPId());
				map.put(mapKey.getKey_accountName(), entityPersonnelInfo.getComId() + "P" + entityPersonnelInfo.getPId());
				map.put("accTypeId", request.getUserData().getAccTypeId());
				map.put(mapKey.getKey_accountState(), 0);
				mqSimpleFeign.AddXFAccount(map);
			}
		}
		else{
			EntityPersonnelInfo entityPersonnelInfo1 = JSON.parseObject(JSON.toJSONString(result4.getData()), EntityPersonnelInfo.class);
            entityPersonnelInfo = entityPersonnelInfo1;
            PersonVo personVo=new  PersonVo();
            personVo.setComId(comId);
            personVo.setPId(entityPersonnelInfo1.getPId());
            personVo.setPCode(pcode);
//            personVo.setPName(request.getUserData().getPName());
            personVo.setDeptId(deptId);
			if(!CommonUtil.isNull(request.getUserData().getIdentity())){
				personVo.setPIdentity(request.getUserData().getIdentity());
			}
			if(!CommonUtil.isNull(request.getUserData().getPhone())){
				personVo.setPPhone(request.getUserData().getPhone());
			}
            personVo.setPSex(request.getUserData().getPSex());
			humanFeignService.UpdatePerson(personVo);
		}

		if(entityPersonnelInfo == null ){
			return ResultUtil.error(ResultEnum.Err_4014);
		}

		Result result7 = humanFeignService.GetWxPerson(request.getAppId(),request.getUserData().getPCode(),comId);
		if(result7.getCode()==200){
			if(result7.getData()==null){
				EntityWechatPerInfo entityWechatPerInfo =new EntityWechatPerInfo();
				entityWechatPerInfo.setAppid(request.getAppId());
				entityWechatPerInfo.setComId(comId);
				entityWechatPerInfo.setPId(entityPersonnelInfo.getPId());
				entityWechatPerInfo.setOpenid(request.getUserData().getPCode());
				humanFeignService.addWxper(entityWechatPerInfo);
			}
		}

		/**
		 * campusName	学校名称	string
		 * pName	用户姓名	string
		 * pCode	用户编号	string
		 * deptName	部门名称	string
		 * pPhotoUrl	人脸头像连接	string
		 */

		Map<String,String> stringStringMap = new HashMap<>();
		stringStringMap.put("campusName","");
		stringStringMap.put("pName",entityPersonnelInfo.getPName());
		stringStringMap.put("pCode",pcode);
		stringStringMap.put("deptName",request.getUserData().getDeptName());
		stringStringMap.put("pPhotoUrl","");
		if(!CommonUtil.isNull(entityPersonnelInfo.getPPhotoUrl())){
			stringStringMap.put("pPhotoUrl",entityPersonnelInfo.getPPhotoUrl());
		}
		if(!CommonUtil.isNull(entityPersonnelInfo.getPPhotoUrl2())){
			stringStringMap.put("pPhotoUrl",entityPersonnelInfo.getPPhotoUrl2());
		}
		return ResultUtil.success(stringStringMap);
	}

	private JHh5 getCompany(String campusId){
		try {
			/**
			 * campusId	学校应用编号	string		是
			 * pName	用户姓名	string		是
			 * pCode	用户编号	string		是
			 */
			GetReplyApiParaRequest getReplyApiParaRequest = new GetReplyApiParaRequest();
			getReplyApiParaRequest.setComAppid(campusId);
			getReplyApiParaRequest.setDockCode("ccbplatform");
			getReplyApiParaRequest.setDockApiCode("ccbplatform#app");
			getReplyApiParaRequest.setKeyType(0);
			Result result2 = companyClientService.getReplyApiPara(getReplyApiParaRequest);

			if (result2.getCode() != 200) {
				return new JHh5(result2.getCode(),result2.getMsg(),campusId,null);
			}
			EntityComDockApi entityComDockApi = JSON.parseObject(JSON.toJSONString(result2.getData()), EntityComDockApi.class);

			return new JHh5(0,"succ",campusId, entityComDockApi.getComId());
		} catch (Exception e) {
			log.info("调用建行h5平台异常【{}】", e);
			return null;
		}
	}



	@Data
	private static class JHh5 {
		//0正常  1 异常
		Integer code;
		String msg;
		String campusId;
		Long comId;

		public JHh5(Integer code,String msg,String campusId, Long comId) {
			this.code = code;
			this.msg = msg;
			this.campusId = campusId;

			this.comId = comId;
		}
	}


}
